<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="店铺名称" prop="storeName">
        <el-input v-model="queryParams.storeName" placeholder="请输入店铺名称" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="店铺账户" prop="storeUserName">
        <el-input v-model="queryParams.storeUserName" placeholder="请输入店铺账户" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">绑定店铺</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border stripe :data="sellerStoreEmpowerList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="店铺自定义名称" align="center" prop="storeName"/>
      <el-table-column label="店铺CN码" align="center" prop="storeUserName"/>
      <el-table-column label="AE授权" align="center" prop="isEmpower">
        <template slot-scope="scope">
          {{ scope.row.isEmpower == '0' ? '未授权' : scope.row.isEmpower == '1' ? '已授权' : '已过期' }}
        </template>
      </el-table-column>
      <el-table-column label="cookie" align="center" prop="storePhone"/>
      <el-table-column label="违规" align="center" prop="storePhone"/>
      <el-table-column label="店铺服务分" align="center" prop="storePhone"/>
      <el-table-column label="消息" align="center" prop="storePhone"/>
      <el-table-column label="绑定时间" align="center" prop="empowerTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.empowerTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button size="mini" type="text" icon="el-icon-link" @click="handleEmpower(scope.row)">基本信息</el-button>-->
          <el-button size="mini" type="text" icon="el-icon-link" @click="handleSelect(scope.row)">店铺类目</el-button>
          <el-button size="mini" type="text" icon="el-icon-link" @click="handleEmpower(scope.row)">解绑店铺</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改卖家店铺授权对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="店铺CN码" prop="storeUserName">
          <el-input v-model="form.storeUserName" placeholder="请输入店铺CN码"/>
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <image-upload v-model="form.businessLicense" :is-show-tip="false"/>
        </el-form-item>
        <el-form-item label="法人名称" prop="storePhone">
          <el-input v-model="form.storePhone" placeholder="请输入法人名称"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看分类 -->
    <el-dialog title="查看分类" :visible.sync="selectOpen" width="50%" append-to-body>
      <template>
        <div v-if="selected.length > 0" class="type-box">
          <el-tag v-for="(item, index) in selected" :key="index">{{ item }}</el-tag>
        </div>
        <div v-else class="type-text">--暂无分类--</div>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="complete(false)">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 登录速卖通授权 -->
    <el-dialog class="empower-dialog" title="" :visible.sync="empowerOpen" width="30%" append-to-body
               @close="openCancel">
      <div class="center-box-item">
        <p>第一步、</p>
        <el-button type="primary" size="medium" @click="buyBtn">购买服务</el-button>
      </div>
      <div class="center-box-item">
        <p>第二步、</p>
        <el-button type="primary" size="medium" @click="signinBtn">登陆速卖通授权</el-button>
      </div>
    </el-dialog>
    <!-- 我已授权 -->
    <el-dialog class="empower-dialog" title="" :visible.sync="isEmpower" width="30%" append-to-body
               @close="empowerCancel">
      <div class="center-box">
        <el-button type="primary" size="medium" @click="empowerCancel">我已授权</el-button>
        <el-button size="medium" @click="empowerCancel">取消</el-button>
      </div>
    </el-dialog>

    <!--  提交cookie弹窗  -->
    <submitCookie v-if="isOpenSubmitCookieModal" @close="closeSubmitCookieModal" :storeId="storeId"
                  :storeUserName="storeUserName"/>
  </div>
</template>

<script>
import {
  listSellerStoreEmpower,
  getSellerStoreEmpower,
  delSellerStoreEmpower,
  addSellerStoreEmpower,
  updateSellerStoreEmpower,
  queryStoreSubCategory,
  selectTopList,
  chooseStoreSubCategory, updateStorePassWord
} from "@/api/shop/index";
import store from '@/store';
import submitCookie from "@/views/shop/components/SubmitCookie.vue";

export default {
  name: "SellerStoreEmpower",
  dicts: ['erp_empower_callback', 'erp_seller_store_type'],
  components: {
    submitCookie
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 卖家店铺授权表格数据
      sellerStoreEmpowerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      selectOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeName: undefined,
        storeEmail: undefined,
        storeUserName: undefined,
        storePassWord: undefined,
        storePhone: undefined,
        isEmpower: undefined,
        empowerTime: undefined,
        userId: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{required: true, message: "主键不能为空", trigger: "blur"}],
        storeName: [{required: true, message: "店铺名称不能为空", trigger: "blur"}],
        // storeType: [
        //   { required: true, message: "店铺类型不能为空", trigger: "blur" }
        // ],
        storeEmail: [{required: true, message: "店铺邮箱不能为空", trigger: "blur"}],
        storeUserName: [{required: true, message: "店铺账户不能为空", trigger: "blur"}],
        storePhone: [{required: true, message: "店铺电话不能为空", trigger: "blur"}],
        businessLicense: [{required: true, message: "请上传营业执照", trigger: "change"}],
        openTime: [{required: true, message: "请选择店铺开通时间", trigger: "change"}]
      },
      // 是否显示弹出层
      empowerOpen: false,
      // 是否授权
      isEmpower: false,
      // 店铺id
      storeId: null,
      storeUserName: "",
      isOpenSubmitCookieModal: false,//是否打开提交cookie弹窗
      // 全选
      checkAll: false,
      // 全选
      isIndeterminate: false,
      // 选中分类列表
      selected: [],
      typeList: [],
      sellerStoreId: '',
      returnFreightList: [
        {
          label: '否',
          value: '0'
        },
        {
          label: '是',
          value: '1'
        }
      ]
    };
  },
  created() {
    this.getList();
    this.getSelectTopList();
  },
  methods: {
    /** 查询卖家店铺授权列表 */
    getList() {
      this.loading = true;
      listSellerStoreEmpower(this.queryParams).then(response => {
        this.sellerStoreEmpowerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        storeName: undefined,
        storeType: 3, // 自营店铺
        storeEmail: undefined,
        storeUserName: undefined,
        storePassWord: undefined,
        storePhone: undefined,
        isEmpower: undefined,
        empowerTime: undefined,
        userId: undefined,
        revision: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        isRetuenFreight: '1' // 退运费
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 关联店铺 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "绑定店铺";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getSellerStoreEmpower(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改店铺信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            console.log('this.form', this.form)
            updateSellerStoreEmpower(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addSellerStoreEmpower(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    // 提交cookie
    handleCookie(row) {
      this.storeId = row.id;
      this.storeUserName = row.storeUserName
      this.isOpenSubmitCookieModal = true
    },
    // 关闭提交cookie弹窗
    closeSubmitCookieModal() {
      this.isOpenSubmitCookieModal = false
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除卖家店铺授权编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delSellerStoreEmpower(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    // 修改密码
    changePassword(row) {
      this.$prompt('请输入密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.+$/,
        inputErrorMessage: '密码不能为空',
        inputValue: row.storePassWord
      }).then(({value}) => {
        let data = {
          storeUserName: row.storeUserName,
          storePassWord: value
        }
        updateStorePassWord(data).then(res => {
          this.$message.success(res.msg)
          this.getList()
        })
      })
    },
    // 授权
    handleEmpower(row) {
      this.storeId = row.id;
      this.empowerOpen = true;
    },
    // 查看分类
    handleSelect(row) {
      this.sellerStoreId = row.id;
      queryStoreSubCategory({sellerId: this.sellerStoreId}).then(res => {
        if (res.data) {
          const typeList = this.typeList;
          const arr = res.data.split(',');
          // console.log('arr', arr, typeList)
          arr.forEach(item => {
            typeList.forEach(cItem => {
              if (item == cItem.id) {
                this.selected.push(cItem.name);
              }
            })
          })
        } else {
          this.selected = [];
        }
        // console.log('selected', this.selected)
        this.selectOpen = true;
      }).finally(() => {

      });
    },
    complete(isSave) {
      if (isSave) {
        const params = {
          userId: store.getters.userId,
          sellerStoreId: this.sellerStoreId,
          categoryIds: this.selected.toString()
        }
        chooseStoreSubCategory(params).then(res => {
          this.$modal.msgSuccess("更新成功");
        }).finally(() => {

        });
      }
      this.selectOpen = false
      this.selected = []
    },
    // 登录速卖通授权
    signinBtn() {
      this.isEmpower = true
      // 打开弹窗跳转登录页面
      window.open(`https://api-sg.aliexpress.com/oauth/authorize?response_type=code&force_auth=true&redirect_uri=${this.dict.type.erp_empower_callback[1].value}?storeId=${this.storeId}&client_id=500890`, "_blank");
    },
    // 购买
    buyBtn() {
      window.open(`https://marketplace.aliexpress.com/web/detail.html?articleCode=FW_GOODS-1001230507`, "_blank");
    },
    // 关闭登陆授权弹框
    openCancel() {
      this.storeId = null
      this.empowerOpen = false;
    },
    // 关闭已授权弹框
    empowerCancel() {
      this.getList();
      this.storeId = null
      this.empowerOpen = false;
      this.isEmpower = false;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('seller/sellerStoreEmpower/export', {
        ...this.queryParams
      }, `sellerStoreEmpower_${new Date().getTime()}.xlsx`)
    },
    // 获取一级分类
    getSelectTopList() {
      this.loading = true;
      selectTopList().then(res => {
        this.typeList = res.data
        this.loading = false;
      });
    }
  }
};
</script>

<style lang="scss">
.empower-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;

  .center-box-item {
    display: flex;
    align-items: center;
    padding: 30px 0 20px 100px;

    &:last-child {
      padding-bottom: 50px;
    }
  }
}

.center-box {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 80px 0 120px;
}

.type-box {
  display: flex;
  flex-wrap: wrap;

  .el-tag {
    margin: 5px;
  }
}

.type-text {
  display: flex;
  justify-content: center;
}
</style>
